// +----------------------------------------------------------------------
// | jufeiniu [干就完了 - JUST DO IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022 https://jufeiniu.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: 乔欣弥弥-巨肥牛 <jufeiniu@163.com>
// +----------------------------------------------------------------------
// | Personal site: https://jufeiniu.com/
// +----------------------------------------------------------------------
import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
// import {
// 	checkLogin
// } from '../libs/login';
// import store from '../store';


function toLogin(){
	// store.commit("LOGOUT");
	
	uni.showToast({
		title: '请登录',
		icon: 'none',
		duration: 1000
	});
	// uni.navigateTo({
	// 	url:'/pages/users/login/index'
	// })

}

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = true,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;

	// if (!noAuth) {
	// 	//登录过期自动登录
	// 	if (!store.state.app.token && !checkLogin()) {
	// 		toLogin();
	// 		return Promise.reject({
	// 			msg: '未登录'
	// 		});
	// 	}
	// }

	// if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: {
				'token':uni.getStorageSync('token')
			},
			data: data || {},
			success: (res) => {
				// console.log(res)
				// #ifdef APP-PLUS
				console.log('app', Url + '/api/' + url, res.data);
				// #endif
				if (noVerify)
					reslove(res.data, res);
				else if (res.statusCode == 200)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 40000].indexOf(res.statusCode) !== -1) {
					toLogin();
					reject(res.data);
				}
			
				 else if (res.statusCode == 501) {
					// uni.reLaunch({
					// 	url: '/pages/error/index'
					// })
					reject(res.data);
				} else
					reject(res.data.message || '系统错误');
			},
			fail: (message) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;
